<?php

namespace App\Admin\Controllers;


use App\Admin\Renderable\UserTable;

use App\Admin\Repositories\Project;
use App\Models\AdminUser;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Auth\Events\Login;
use Illuminate\Support\Facades\Log;

class ProjectDisPatchController extends AdminController
{
    public function title()
    {
        return '项目分配';
    }
    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Project(), function (Form $form) {
            $form->tools(function (Form\Tools $tools) {
                $tools->append('<a href="javascript:history.back(-1)" class="btn btn-primary dialog-create">列表</a>');
            });
            $form->disableCreatingCheck();
            $form->disableViewCheck();
            $form->disableListButton();
            $form->disableDeleteButton();
            $form->disableViewButton();
            $form->disableEditingCheck();
            // $form->selectTable('worker_user_id', '负责人')->form(UserTable::make(['company_id' => $form->model()->company_id]))->options(Project::getWorkerList());
            $form->display('project_name', '项目名称');
            $form->display('active_name', '活动名称');
            $admin = Admin::user();
            if ($admin->isAdministrator() || $admin->isRole('项目经理')) {
                $options = AdminUser::where('status', 1)->pluck('name', 'id');
            } elseif ($admin->isRole('project-manager')) {
                $options = AdminUser::where(['status' => 1, 'company_id' => $form->model()->company_id])->pluck('name', 'id');
            } elseif ($admin->isRole('regional-supervisor')) {
                $options = AdminUser::where(['status' => 1, 'company_id' => $form->model()->company_id, 'region' => $admin->region])->pluck('name', 'id');
            }

            $form->multipleSelectTable('worker_user_id', '负责人')
                ->title('负责人')
                // ->max(4)
                ->from(UserTable::make(['company_id' => $form->model()->company_id]))
                // ->model(AdminUser::class, 'id', 'name')
                ->options($options)
                ->customFormat(function ($name) use ($options) {
                    // 当前角色可以看到的用户
                    $currLoginRoleUser = array_keys($options->toArray());
                    // dd($currLoginRoleUser);
                    // $name  就是现在表中现有的用户
                    // 过滤一下当前用户能看到
                    $result = [];
                    foreach (explode(',', $name) as $val) {
                        if (in_array($val, $currLoginRoleUser)) {
                            $result[] = $val;
                        }
                    }
                    // dd($result);
                    return implode(',', $result);
                })
                ->saving(function ($value) {
                    return implode(',', $value);
                });
            $form->hidden('worker_user_name');

            $form->saving(function (Form $form) use ($options) {
                // 当前角色可以看到的用户
                $currLoginRoleUser = array_keys($options->toArray());
                // dd($currLoginRoleUser);
                // 原始数据
                $original = explode(',', $form->model()->worker_user_id);
                $isExist = [];
                $notExist = [];
                // 提交数据
                $formData = explode(',', $form->input('worker_user_id'));
                foreach ($formData as $val) {
                    if (in_array($val, $original)) {
                        $isExist[] = $val;
                    } else {
                        $notExist[] = $val;
                    }
                }
                // 当前角色可以看的用户和提交数据做差异对比
                $diffData = array_diff($currLoginRoleUser, $formData);
                // dump($diffData);
                // 合并数组
                $new_worker_user_id = array_merge($original, $isExist, $notExist);
                // 数组去重
                $uniqueData = array_unique($new_worker_user_id);

                // 把差异去除
                $array = array_diff($uniqueData, $diffData);
                if (!(Admin::user()->isAdministrator()) && !(Admin::user()->isRole('项目经理'))) {
                    if (!in_array(Admin::user()->id, $array)) {
                        return $form->response()->error('请勿删除自己');
                    }
                }

                // dump($array);
                $worker = AdminUser::whereIn('id', $array)
                    ->select('name')
                    ->pluck('name')
                    ->toArray();
                // dd($worker);
                $form->worker_user_id = implode(',', $array);
                $form->worker_user_name = implode(' | ', $worker);
            });
            $form->saved(function (Form $form) {
                $data = $form->updates();
                Log::info(' ====== 项目分配最终结果： ====== ' . json_encode($data));
                return $form->response()->success('保存成功')->redirect('project');
            });

            //
        });
    }
}
